---
title: Filters
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

Filters provide an easy way of cleaning HTML attributes and nodes during the
[parsing cycle](./parser.md). This is especially useful for `src` and `href` attributes.

## Usage

Filters can be added to each instance of `<Interweave />` through the `filters` prop.

```tsx
<Interweave filters={[new LinkFilter()]} />
```

To disable all filters, pass the `disableFilters` prop.

```tsx
<Interweave disableFilters />
```

## Creating a filter

Creating a custom filter is easy. Extend the base `Filter` class, or use a plain object, and define
the `attribute` or `node` methods. These methods receive the attribute or tag name as the 1st
argument, and the value as the 2nd, respectively.

<Tabs
  groupId="filter-type"
  defaultValue="class"
  values={[
    { label: 'Class', value: 'class' },
    { label: 'Object', value: 'object' },
  ]}
>
  <TabItem value="class">

```tsx
import { Filter } from 'interweave';

class LinkFilter extends Filter {
	attribute(name: string, value: string): string {
		if (name === 'href') {
			return encodeURIComponent(value);
		}

		return value;
	}

	node(name: string, node: HTMLElement): HTMLElement {
		if (name === 'a') {
			node.setAttribute('target', '_blank');
		}

		return node;
	}
}

const filter = new LinkFilter();
```

  </TabItem>
  <TabItem value="object">

```tsx
import { FilterInterface } from 'interweave';

const filter: FilterInterface = {
	attribute(name, value) {
		if (name === 'href') {
			return encodeURIComponent(value);
		}

		return value;
	},
	node(name, node) {
		if (name === 'a') {
			node.setAttribute('target', '_blank');
		}

		return node;
	},
};
```

  </TabItem>
</Tabs>

> Attribute values and nodes must be returned from filter methods!

> Returning `null` for a node will remove it from the DOM tree.
